﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using AcsCommon;

namespace YiShi.Class
{
    public abstract class DbObject
    {
        protected DbAccess db;
        protected DataRecord dr;
        protected string fullTableName;
        public string Id 
        { 
            get
            {
                return dr["Id"];
            }
            set
            {
                dr["Id"] = value;
            }
        }
        public DbObject(DbAccess db, string fullTableName)
        {
            this.db = db;
            this.fullTableName = fullTableName;
            dr = new DataRecord(fullTableName);
        }
        public virtual void Fill(HttpRequest request)
        {
            string[] props = DataExt.GetProperties(this.GetType());
            foreach (string prop in props)
            {
                this.SetPropertyValue(prop, request[prop]);
            }
        }
        public virtual void FillFromDb(string id)
        {
            DataRecord dr = this.db.SelectRecord(this.fullTableName, id);
            dr.FillObject(this);
        }
        public virtual void FillFromDb(string fields, string fieldName, object fieldValue)
        {
            DataRecord dr = this.db.SelectRecord(this.fullTableName, fields, fieldName, fieldValue);
            dr.FillObject(this);
        }
        public virtual void Delete()
        {
            this.db.DeleteRecord(this.dr);
        }
        public abstract void Update();
        protected void Update(string idKey)
        {
            if (string.IsNullOrEmpty(dr["Id"]))
            {
                dr["Id"] = IdFactory.Get(idKey);
                db.InsertRecord(dr);
            }
            else
                db.UpdateRecord(dr);
        }
    }
}
